package com.multiplepb.controller;

import com.microsoft.playwright.*;
import com.multiplepb.bean.BrowserEnum;
import com.multiplepb.bean.CommonInfoType;
import com.multiplepb.config.StageRouter;
import com.multiplepb.entity.CommonInfo;
import com.multiplepb.mapper.CommonInfoDao;
import com.multiplepb.utils.TimeUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

/**
 * @author 单耀
 * @date 2025/1/25 17:30
 */
@Slf4j
@Controller
public class PbMulPlatformController implements Initializable {
    private final StageRouter router;
    public PbMulPlatformController(StageRouter router) {
        this.router = router;
    }
    @Autowired
    private CommonInfoDao commonInfoDao;
    @FXML
    private CheckBox bPlatId;
    @FXML
    private TextField browserCacheFolderId;
    @FXML
    private TextField tagId;
    @FXML
    private TextField videoTitleId;
    public static Page.WaitForSelectorOptions waitForSelectorOptions = new Page.WaitForSelectorOptions().setTimeout(1000 * 60 * 1);
    @FXML
    void pbToPlatsAction(ActionEvent event) throws InterruptedException {

        //选择视频
        File videoFile = getVideoFile(null);
        if (videoFile == null) {
            Alert alert = new Alert(Alert.AlertType.WARNING, "请选择视频文件");
            alert.getButtonTypes().add(new ButtonType("确认", ButtonBar.ButtonData.OK_DONE));
            alert.showAndWait();
            return;
        }

        if (videoTitleId.getText() == null) {
            Alert alert = new Alert(Alert.AlertType.WARNING, "请填写视频标题");
            alert.getButtonTypes().add(new ButtonType("确认", ButtonBar.ButtonData.OK_DONE));
            alert.showAndWait();
            return;
        }
        Playwright playwright = Playwright.create();
        BrowserType chromium = playwright.chromium();
        String browserEnumValue = BrowserEnum.google.getValue();

        BrowserContext browserContext = chromium.launchPersistentContext(Path.of("G:\\cache"),
                new BrowserType.LaunchPersistentContextOptions()
                        .setHeadless(false)
                        .setArgs(Arrays.asList("--start-maximized"))
                        .setChannel(browserEnumValue)
                        .setViewportSize(null)
        );
        Page page = browserContext.newPage();
        page.navigate("https://member.bilibili.com/platform/home");
        ElementHandle navUploadBtn = page.waitForSelector("#nav_upload_btn");
        navUploadBtn.click();

      /*  ElementHandle bccUploadWrapper = page.waitForSelector(".bcc-upload-wrapper");
        ElementHandle uploadInput = bccUploadWrapper.querySelector("input[type=file]");
        uploadInput.setInputFiles(Paths.get("G:\\自媒体\\课程\\批量发布工具课程\\测试视频\\测试.mp4"));
*/

        //如果没有输入元素
       FileChooser fileChooser = page.waitForFileChooser(() ->
                page.waitForSelector(".bcc-upload-wrapper").click());



//        fileChooser.setFiles(Paths.get("G:\\自媒体\\课程\\批量发布工具课程\\测试视频\\测试.mp4"));
        fileChooser.setFiles(Paths.get(videoFile.getAbsolutePath()));

        //标题
        TimeUnit.MILLISECONDS.sleep(500);
        ElementHandle videoTitle = page.waitForSelector(".video-title-content");
        ElementHandle titleInput = videoTitle.querySelector("input[type=text]");
        titleInput.fill(videoTitleId.getText());
        String tagString = tagId.getText();
        if (tagString != null) {
            String tagReplace = tagString.replace("，", ",");
            String[] split = tagReplace.split(",");
            List<String> tagList = List.of(split);
            ElementHandle tagContainer = page.waitForSelector("#tag-container");
            ElementHandle tagInput = tagContainer.waitForSelector("input[type='text']");
            for (String tag : tagList) {
                tagInput.fill(tag);
                page.keyboard().press("Enter");
                TimeUnit.MILLISECONDS.sleep(500);
            }
        }
//        List<String> tagList = Arrays.asList("测试","张三","影视");

//定时发布
        LocalDate delayDayValue = LocalDate.of(2025,2,10);
        if (delayDayValue != null) {
            ElementHandle timeCon = page.waitForSelector(".time-container");
            ElementHandle timeSwitch = timeCon.waitForSelector(".switch-container");
            timeSwitch.click();
            TimeUnit.MILLISECONDS.sleep(500);
            ElementHandle pickerWrpDate = timeCon.querySelectorAll(".date-picker-date-wrp").get(0);
            ElementHandle picker = pickerWrpDate.waitForSelector(".date-picker-date");
            picker.click();
            TimeUnit.MILLISECONDS.sleep(500);
            ElementHandle dateCon = pickerWrpDate.waitForSelector(".date-picker-container");
            ElementHandle navWrp = dateCon.waitForSelector(".date-picker-nav-wrp");
            ElementHandle nextBtn = navWrp.querySelectorAll("svg").get(2);
            int dateInterval = TimeUtils.getDateIntervalFromNow(delayDayValue);
            for (int i = 0; i < dateInterval; i++) {
                nextBtn.click();
            }
            String publishTime = "23:30";
            if (publishTime != null) {
                ElementHandle pickerWrpTime = timeCon.querySelectorAll(".date-picker-date-wrp").get(1);
                pickerWrpTime.click();
                TimeUnit.MILLISECONDS.sleep(100);
                String[] split = publishTime.split(":");
                ElementHandle hour = pickerWrpTime.querySelectorAll(".time-picker-panel-select-wrp").get(0);
                hour.querySelector("span:has-text('" + split[0] + "')").click();
                ElementHandle ms = pickerWrpTime.querySelectorAll(".time-picker-panel-select-wrp").get(1);
                ms.querySelector("span:has-text('" + split[1] + "')").click();
            }


        }
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        try {
            CommonInfo commonInfo = commonInfoDao.selectByType(CommonInfoType.browser_cache_path.getValue());
            if (commonInfo != null && commonInfo.getCommonValue() != null) {
                browserCacheFolderId.setText(commonInfo.getCommonValue());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @FXML
    public void setBrowserCacheAction(ActionEvent actionEvent) {
        try {
            // 在某个事件处理程序中创建 DirectoryChooser 对象
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择文件夹");
            // 显示文件选择对话框并等待用户选择
            File selectedDirectory = directoryChooser.showDialog(new Stage());
            if (selectedDirectory != null) {
                // 用户选择了一个目录
                System.out.println("用户选择的目录为: " + selectedDirectory.getAbsolutePath());
                browserCacheFolderId.setText(selectedDirectory.getAbsolutePath());
                commonInfoDao.insertOrReplace(selectedDirectory.getAbsolutePath(), CommonInfoType.browser_cache_path.getValue());

            } else {
                // 用户取消了操作
                System.out.println("用户取消了选择操作。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private File getVideoFile(String filePath) {
        List<String> videSuffix = Arrays.asList("*.mp4", "*.avi", "*.mkv", "*.mov", "*.wmv", "*.webm");
        return getFile(filePath, videSuffix);
    }
    private File getFile(String filePath, List<String> suffixs) {
        // 实例化一个文件选择器
        javafx.stage.FileChooser fileChooser = new javafx.stage.FileChooser();
        // 设置标题和默认目录
        fileChooser.setTitle("选择文件");
        if (filePath == null) {
            filePath = "C:\\";
        }
        fileChooser.setInitialDirectory(new File(filePath));
        // 添加文件过滤器，仅允许选择文本文件
        if (suffixs != null && suffixs.size() > 0) {
            fileChooser.getExtensionFilters().addAll(
                    new javafx.stage.FileChooser.ExtensionFilter("Audio Files", suffixs));
        } else {
            fileChooser.getExtensionFilters().addAll(
                    new javafx.stage.FileChooser.ExtensionFilter("Audio Files", "*.*"));
        }

        // 打开文件选择对话框
        File selectedFile = null;
        try {
            selectedFile = fileChooser.showOpenDialog(null);
        } catch (Exception e) {
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); // 设置打开窗口时的默认目录
            selectedFile = fileChooser.showOpenDialog(new Stage());
        }
        if (selectedFile == null) {
            return null;
        }
        return selectedFile;
    }
}
